const Koa = require('koa')
const router = require('koa-router')()
const IO = require('koa-socket')
const cors = require('koa2-cors')
const { join } = require('path')
const url = require('url')
const fs = require('fs')
const io = new IO();

let app = new Koa();
const port = 22335

app.use(cors({
    origin: '*',
    exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
    maxAge: 5,
    credentials: true,
    allowMethods: ['GET', 'POST', 'DELETE'],
    allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
}))

router.get("/", async ctx => {
    ctx.body = fs.readFileSync(join(__dirname, 'public', "index.html"), "utf8", (err, data) => {
        if (err) throw err;
        if (data) {
            return data;
        }
    })
});
router.get("/sync", async ctx => {
    ctx.body = fs.readFileSync(join(__dirname, 'public', "ctrl_c_sync.html"), "utf8", (err, data) => {
        if (err) throw err;
        if (data) {
            return data;
        }
    })
});
router.get("/log-client.js", async ctx => {
    ctx.body = fs.readFileSync(join(__dirname, 'public', "log-client.js"), "utf8", (err, data) => {
        if (err) throw err;
        if (data) {
            return data
        }
    }).toString('utf-8').replace('${serverHost}', 'http://' + ctx.request.host)
});
router.get("/ctrl_c_sync.js", async ctx => {
    ctx.body = fs.readFileSync(join(__dirname, 'public', "ctrl_c_sync.js"), "utf8", (err, data) => {
        if (err) throw err;
        if (data) {
            return data
        }
    }).toString('utf-8').replace('${serverHost}', 'http://' + ctx.request.host)
});
router.get("/log-browser.js", async ctx => {
    ctx.body = fs.readFileSync(join(__dirname, 'public', "log-browser.js"), "utf8", (err, data) => {
        if (err) throw err;
        if (data) {
            return data;
        }
    }).toString('utf-8').replace('${serverHost}', 'http://' + ctx.request.host)
});

app.use(router.routes()).use(router.allowedMethods());

io.attach(app);
app._io.on('connection', socket => {
    let roomid = new url.URL('http://localhost' + socket.request.url).searchParams.get('roomid') || 'client'
    socket.join(roomid);
    if (roomid == 'log') console.log('日志输出页面可用')
    socket.on('log', (...data) => {
        socket.broadcast.to('log').emit('browserLog', ...data)
    });
    socket.on('ctrl_c', (...data) => {
        socket.broadcast.to('sync').emit('ctrl_c', ...data)
    })
    socket.on('err', (...data) => {
        socket.broadcast.to('log').emit('browserErr', ...data)
    })
    socket.on('disconnect', () => {
        console.log('disconnect')
    })
    socket.on('connect', () => {
        console.log('connect')
    })
})

app.listen(port, () => {
    console.log('日志服务启动 端口:' + port, 'http://localhost:' + port)
});